<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="员工姓名" size="small">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <!--<el-col class="other">-->
        <!--<el-form-item prop="teamName" label="团队/部门" size="small" class="item-inline">-->
        <!--<el-input v-model="searchForm.teamName"></el-input>-->
        <!--</el-form-item>-->
        <!--</el-col>-->
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <!--<el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>-->
      <!--<el-button size="small" icon="el-icon-upload2" @click="downloadFile">导入</el-button>-->
      <input class="file" type="file" @change="fileChanged" ref="file"/>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="1000px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="120px">
          <el-row>
            <el-col class="other">
              <el-form-item label="分类" size="small" class="item-inline">
                <el-select v-model="teamRow.classification" placeholder="请选择">
                  <el-option
                    v-for="item in global.classificationList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="二级部门" size="small" class="item-inline">
                <el-select v-model="teamRow.secondarySector" placeholder="请选择">
                  <el-option
                    v-for="item in global.secondarySectorList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职级" size="small" class="item-inline">
                <el-select v-model="teamRow.rank" placeholder="请选择">
                  <el-option
                    v-for="item in global.rankList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="tel" label="联系电话" size="small" class="item-inline">
                <el-input v-model="teamRow.tel"></el-input>
              </el-form-item>
              <el-form-item label="职业注册" size="small" class="item-inline">
                <el-input v-model="teamRow.professionalRegistered"></el-input>
              </el-form-item>
            </el-col>
            <el-col class="other">
              <el-form-item label="类型" size="small" class="item-inline">
                <el-select v-model="teamRow.genre" placeholder="请选择">
                  <el-option
                    v-for="item in global.genreList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="teamName" label="团队/部门" size="small" class="item-inline">
                <el-autocomplete
                  v-model="teamRow.teamName"
                  :fetch-suggestions="querySearchTeam"
                  @select="handleSelectTeam"
                  placeholder="请输入内容"
                >
                </el-autocomplete>
              </el-form-item>
              <el-form-item prop="name" label="姓名" size="small" class="item-inline">
                <el-input v-model="teamRow.name"></el-input>
              </el-form-item>
              <el-form-item prop="hireDate" label="入职日期" size="small">
                <el-date-picker
                  v-model="teamRow.hireDate"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择日期"
                  style="width: 190px">
                </el-date-picker>
              </el-form-item>
              <el-form-item prop="socialSecurity.insuredStatus" label="社保参保状态" size="small"
                            class="item-inline">
                <el-select v-model="teamRow.socialSecurity.insuredStatus" placeholder="请选择">
                  <el-option
                    v-for="item in global.insuredStatusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col class="other">
              <el-form-item label="一级部门" size="small" class="item-inline">
                <el-select v-model="teamRow.primarySector" placeholder="请选择">
                  <el-option
                    v-for="item in global.primarySectorList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="职务" size="small" class="item-inline">
                <el-input v-model="teamRow.position"></el-input>
              </el-form-item>
              <el-form-item prop="sex" label="性别" size="small">
                <el-radio-group v-model="teamRow.sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="0">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="技术职称" size="small" class="item-inline">
                <el-input v-model="teamRow.jobTitle"></el-input>
              </el-form-item>
              <el-form-item prop="accumulationFund.insuredStatus" label="公积金参缴状态" size="small" class="item-inline">
                <el-select v-model="teamRow.accumulationFund.insuredStatus" placeholder="请选择">
                  <el-option
                    v-for="item in global.insuredStatusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!--<div slot="footer" class="dialog-footer">-->
        <!--<el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>-->
        <!--<el-button size="small" @click="outerVisible = false">取消</el-button>-->
        <!--</div>-->
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.employeeId)"
            type="text"
            size="small">
            查看
          </el-button>
          <!--<el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
          -->
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    addEmployee,
    changeEmployee,
    delEmployee,
    findInfoById,
    getListEmployee,
    selectTeam,
    downloadRoster
  } from '@/api/roster'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { Message } from 'element-ui'
  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'
  import { isvalidPhone } from '@/utils/validate'

  const hireDate = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const sex = function(row, column) {
    return row.sex ? '男' : '女'
  }

  const formatter = function(row, column) {
    if (row[column.property]) {
      let obj = {}
      obj = global[`${column.property}List`].find((item) => {
        return item.value === row[column.property] // 筛选出匹配数据
      })
      return obj.label
    }
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入联系电话'))
        } else if (!isvalidPhone(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      const validPhone1 = (rule, value, callback) => {
        if (!value) {
          callback()
        } else if (!isvalidPhone(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        colConfigs: [
          { prop: 'teamName', label: '团队/部门', width: '150', fixed: true },
          { prop: 'position', label: '职务', width: '150' },
          { prop: 'rank', label: '职级', width: '150', formatter: formatter },
          { prop: 'name', label: '姓名', width: '150' },
          { prop: 'sex', label: '性别', width: '150', formatter: sex },
          { prop: 'tel', label: '联系电话', width: '150' },
          { prop: 'hireDate', label: '入职时间', width: '150', component: hireDate },
          { prop: 'jobTitle', label: '技术职称', width: '150' },
          { prop: 'professionalRegistered', label: '职业注册', width: '150' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        teams: [],
        roles: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增员工',
        dialogType: 0,
        teamRow: {
          socialSecurity: {},
          accumulationFund: {}
        },
        teamRowClear: {},
        socialSecurity: {},
        accumulationFund: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        pca: pca,
        rules: {
          teamName: [
            { required: true, message: '请选择团队', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入员工姓名', trigger: 'change' }
          ],
          sex: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          idNumber: [
            { required: true, message: '请输入身份证', trigger: 'change' }
          ],
          tel: [
            { required: true, trigger: 'change', validator: validPhone }
          ],
          hireDate: [
            { required: true, message: '请选择入职时间', trigger: 'change' }
          ],
          contractStartTime: [
            { required: true, message: '请选择合同起始时间', trigger: 'change' }
          ],
          contractExpired: [
            { required: true, message: '请选择合同结束时间', trigger: 'change' }
          ],
          age: [
            { required: true, message: '请输入司龄', trigger: 'change' }
          ],
          homePhone: [
            { required: false, trigger: 'change', validator: validPhone1 }
          ],
          socialSecurity: {
            insuredStatus: [
              { required: true, message: '请输入参保状态', trigger: 'change' }
            ]
          },
          accumulationFund: {
            insuredStatus: [
              { required: true, message: '请输入参保状态', trigger: 'change' }
            ]
          }
        },
        visible: false,
        isDisabled: false,
        photoPath: {},
        entryForm: {},
        householdNatureList: [{
          value: 1,
          label: '农村户口'
        }, {
          value: 2,
          label: '城镇户口'
        }],
        educationList: [{
          value: 1,
          label: '初中'
        }, {
          value: 2,
          label: '高中'
        }, {
          value: 3,
          label: '大专'
        }, {
          value: 4,
          label: '本科'
        }, {
          value: 5,
          label: '硕士'
        }, {
          value: 6,
          label: '博士'
        }, {
          value: 7,
          label: '其他'
        }]
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      teamId() {
        return this.$store.state.user.teamId
      },
      isDirector() {
        return this.$store.state.user.isDirector
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.isDirector = this.isDirector
        this.searchFormList.teamId = this.teamId
        this.listLoading = true
        getListEmployee(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isDisabled = false
        this.dialogTitle = '新增员工'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs.infoFile) {
          this.$refs.infoFile.value = ''
        }
      },
      editTeam(employeeId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isDisabled = true
        this.dialogTitle = '修改员工'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        if (this.$refs.infoFile) {
          this.$refs.infoFile.value = ''
        }
        const params = {
          employeeId: employeeId
        }
        findInfoById(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
        })
      },
      submitForm(formName) {
        const params = {
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          name: this.teamRow.name,
          sex: this.teamRow.sex,
          idNumber: this.teamRow.idNumber,
          tel: this.teamRow.tel,
          hireDate: this.teamRow.hireDate,
          contractStartTime: this.teamRow.contractStartTime,
          contractExpired: this.teamRow.contractExpired,
          socialSecurity: this.teamRow.socialSecurity,
          accumulationFund: this.teamRow.accumulationFund,
          age: this.teamRow.age,
          employeeCode: this.teamRow.employeeCode ? this.teamRow.employeeCode : '',
          position: this.teamRow.position ? this.teamRow.position : '',
          education: this.teamRow.education ? this.teamRow.education : '',
          graduationSchool: this.teamRow.graduationSchool ? this.teamRow.graduationSchool : '',
          professional: this.teamRow.professional ? this.teamRow.professional : '',
          graduationTime: this.teamRow.graduationTime ? this.teamRow.graduationTime : '',
          professionalYear: this.teamRow.professionalYear ? this.teamRow.professionalYear : '',
          email: this.teamRow.email ? this.teamRow.email : '',
          jobTitle: this.teamRow.jobTitle ? this.teamRow.jobTitle : '',
          certificateNum: this.teamRow.certificateNum ? this.teamRow.certificateNum : '',
          certificateTime: this.teamRow.certificateTime ? this.teamRow.certificateTime : '',
          professionalRegistered: this.teamRow.professionalRegistered ? this.teamRow.professionalRegistered : '',
          professionalCertificate: this.teamRow.professionalCertificate ? this.teamRow.professionalCertificate : '',
          birthday: this.teamRow.birthday ? this.teamRow.birthday : '',
          stampNum: this.teamRow.stampNum ? this.teamRow.stampNum : '',
          signNum: this.teamRow.signNum ? this.teamRow.signNum : '',
          urgentPeople: this.teamRow.urgentPeople ? this.teamRow.urgentPeople : '',
          homePhone: this.teamRow.homePhone ? this.teamRow.homePhone : '',
          relation: this.teamRow.relation ? this.teamRow.relation : '',
          marriage: this.teamRow.marriage ? this.teamRow.marriage : '',
          birthPlace: this.teamRow.birthPlace ? this.teamRow.birthPlace : '',
          householdNature: this.teamRow.householdNature ? this.teamRow.householdNature : '',
          residenceAddress: this.teamRow.residenceAddress ? this.teamRow.residenceAddress : '',
          currentAddress: this.teamRow.currentAddress ? this.teamRow.currentAddress : '',
          archivesAddress: this.teamRow.archivesAddress ? this.teamRow.archivesAddress : ''
        }
        if (!this.dialogType) {
          params.employeeId = this.teamRow.employeeId
        }
        if (this.teamRow.teamId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addEmployee(params).then(response => {
                  this.outerVisible = false
                  this.fetchData()
                })
              } else {
                changeEmployee(params).then(response => {
                  this.outerVisible = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          employeeId: scope.row.employeeId,
          isDel: 1
        }
        delEmployee(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        if (queryString) {
          const params = {
            teamName: queryString
          }
          selectTeam(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.teamName
            }
            let nameList = response.responseBody
            if (nameList.length === 0) {
              nameList = [{ value: '暂无数据' }]
            }
            callback(nameList)
          })
        } else {
          callback([])
        }
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
      },
      downloadFile() {
        this.$refs.file.click()
      },
      fileChanged() {
        const excel = this.$refs.file.value
        const params = new FormData()
        console.log(this.$refs.file.value)
        var reg = /^.*\.(?:xls|xlsx)$/i
        if (!reg.test(excel)) {
          Message({
            message: '请上传excel格式的文件!',
            type: 'error',
            duration: 5 * 1000
          })
          return
        } else {
          params.append('file', this.$refs.file.files[0])
          downloadRoster(params).then(response => {
            this.fetchData()
          })
          if (this.$refs.file) {
            this.$refs.file.value = ''
          }
        }
      }
    },
    mounted() {
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
      .file {
        display: none;
      }
    }
    .active-pic {
      font-size: 0.6rem;
      color: #9b9b9b;
      padding: 0 1rem 0 1.5rem;
      margin-top: 1rem;
    }
    .fileHidden {
      display: none;
    }
    .imgSrc {
      position: relative;
      width: 215px;
      height: 300px;
      img {
        width: 100%;
        height: 100%;
        border-radius: 6px;
      }
      i {
        position: absolute;
        top: 10px;
        right: 10px;
        cursor: pointer;
      }
    }
    .imgPlus {
      width: 215px;
      height: 300px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30px;
      &:hover {
        border-color: #409EFF;
      }
    }
    .entryFormSrc {
      position: relative;
      width: 100%;
      min-height: 300px;
      img {
        width: 100%;
        height: 100%;
        border-radius: 6px;
      }
      i {
        position: absolute;
        top: 10px;
        right: 10px;
        cursor: pointer;
      }
    }
    .entryFormPlus {
      width: 100%;
      height: 300px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30px;
      &:hover {
        border-color: #409EFF;
      }
    }
    .other {
      width: 300px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
  background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
  background-color: #0000ff !important;
  }*/
</style>
